package com.ruoyi.warning.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.xuehua.SnowflakeIdUtils;
import com.ruoyi.control.service.IJingxiaHistoryService;
import com.ruoyi.safety.service.ISafetyPointRealHistoryService;
import com.ruoyi.warning.domain.EarlyWarningSetting;
import com.ruoyi.warning.domain.WarningRecord;
import com.ruoyi.warning.dto.EarlyWarningSettingDto;
import com.ruoyi.warning.mapper.WarningRecordMapper;
import com.ruoyi.warning.service.IEarlyWarningSettingService;
import com.ruoyi.warning.service.IWarningRecordService;
import com.ruoyi.system.mapper.SysDictDataMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 预警记录Service业务层处理
 *
 * @author ruoyi
 * @date 2024-11-24
 */
@Service
public class WarningRecordServiceImpl extends ServiceImpl<WarningRecordMapper, WarningRecord> implements IWarningRecordService //修改
{
    @Autowired
    private WarningRecordMapper warningRecordMapper;

    @Autowired
    private IEarlyWarningSettingService earlyWarningSettingService;

    @Autowired
    private SysDictDataMapper sysDictDataMapper;

    @Autowired
    private ISafetyPointRealHistoryService safetyPointRealHistoryService;

    @Autowired
    private IJingxiaHistoryService jingxiaHistoryService;

    @Autowired
    private IWarningRecordService warningRecordService;


    /**
     * 查询预警记录
     *
     * @param warningRecordId 预警记录主键
     * @return 预警记录
     */
    @Override
    public WarningRecord selectWarningRecordByWarningRecordId(String warningRecordId) {
        return warningRecordMapper.selectWarningRecordByWarningRecordId(warningRecordId);
    }

    /**
     * 查询预警记录列表
     *
     * @param warningRecord 预警记录
     * @return 预警记录
     */
    @Override
    public List<WarningRecord> selectWarningRecordList(WarningRecord warningRecord) {
        return warningRecordMapper.selectWarningRecordList(warningRecord);
    }

    @Scheduled(fixedRate = 60000) // 每 60 秒执行一次
    public void executeScheduledTask() {
//        System.out.println("定时任务触发...");
        // 调用业务逻辑方法
        List<WarningRecord> records = this.selectWarningRecordListAll(new WarningRecord());
        // 处理返回的数据
//        System.out.println("查询结果数量：" + records.size());
    }

    /**
     * 查询预警记录列表安全+水文
     *
     * @param warningRecord 预警记录
     * @return 预警记录集合
     */
    @Override
    public List<WarningRecord> selectWarningRecordListAll(WarningRecord warningRecord) {
        //获取预警设置list
        List<EarlyWarningSettingDto> earlyWarningSettingDtoList = getEarlyWarningSettingDto();
        List<EarlyWarningSettingDto> collect = earlyWarningSettingDtoList.stream().map(earlyWarningSettingDto -> {
            // 创建 DecimalFormat 实例，设置保留五位小数
            DecimalFormat df = new DecimalFormat("#.#####");
            WarningRecord warningRecord1 = new WarningRecord();
            if (earlyWarningSettingDto.getSystemTypeName().contains("安全")) {
                //获取阈值
                Double warningThreshold = Double.valueOf(earlyWarningSettingDto.getWarningThreshold());
                //获取近3天平均值
                if (safetyPointRealHistoryService.selectSafetyPointRealHistoryListThreeAvg(earlyWarningSettingDto.getSensorTypeName(), earlyWarningSettingDto.getBaseStationName()) == null) {
                    return null;
                }
                Double threeAvg = Double.valueOf(safetyPointRealHistoryService.selectSafetyPointRealHistoryListThreeAvg(earlyWarningSettingDto.getSensorTypeName(), earlyWarningSettingDto.getBaseStationName()));
                //获取近一天平均值
                if (safetyPointRealHistoryService.selectSafetyPointRealHistoryListOneAvg(earlyWarningSettingDto.getSensorTypeName(), earlyWarningSettingDto.getBaseStationName()) == null) {
                    return null;
                }
                Double oneAvg = Double.valueOf(safetyPointRealHistoryService.selectSafetyPointRealHistoryListOneAvg(earlyWarningSettingDto.getSensorTypeName(), earlyWarningSettingDto.getBaseStationName()));
                //获取自定义时间平均值
                Double customTimeAvg = null;
                if (earlyWarningSettingDto.getWarningTimeUnitName().equals("小时")) {
                    Double warningTime = Double.valueOf(earlyWarningSettingDto.getWarningTime());
                    String customTimeCount = String.valueOf(warningTime * 3600);
                    if (safetyPointRealHistoryService.selectSafetyPointRealHistoryListCustomTime(earlyWarningSettingDto.getSensorTypeName(), earlyWarningSettingDto.getBaseStationName(), customTimeCount) == null) {
                        return null;
                    }
                    customTimeAvg = Double.valueOf(safetyPointRealHistoryService.selectSafetyPointRealHistoryListCustomTime(earlyWarningSettingDto.getSensorTypeName(), earlyWarningSettingDto.getBaseStationName(), customTimeCount));
                }
                if (earlyWarningSettingDto.getWarningTimeUnitName().equals("分钟")) {
                    Double warningTime = Double.valueOf(earlyWarningSettingDto.getWarningTime());
                    String customTimeCount = String.valueOf(warningTime * 60);
                    if (safetyPointRealHistoryService.selectSafetyPointRealHistoryListCustomTime(earlyWarningSettingDto.getSensorTypeName(), earlyWarningSettingDto.getBaseStationName(), customTimeCount) == null) {
                        return null;
                    }
                    customTimeAvg = Double.valueOf(safetyPointRealHistoryService.selectSafetyPointRealHistoryListCustomTime(earlyWarningSettingDto.getSensorTypeName(), earlyWarningSettingDto.getBaseStationName(), customTimeCount));
                }
                if (earlyWarningSettingDto.getWarningTimeUnitName().equals("秒")) {
                    if (safetyPointRealHistoryService.selectSafetyPointRealHistoryListCustomTime(earlyWarningSettingDto.getSensorTypeName(), earlyWarningSettingDto.getBaseStationName(), earlyWarningSettingDto.getWarningTime()) == null) {
                        return null;
                    }
                    customTimeAvg = Double.valueOf(safetyPointRealHistoryService.selectSafetyPointRealHistoryListCustomTime(earlyWarningSettingDto.getSensorTypeName(), earlyWarningSettingDto.getBaseStationName(), earlyWarningSettingDto.getWarningTime()));
                }
//                System.out.println("customTimeAvg = " + customTimeAvg);
                //定义分析结果描述
                String analysisResultDescriptionWarning = "检测点最近" + earlyWarningSettingDto.getWarningTime() + earlyWarningSettingDto.getWarningTimeUnitName() + "的平均值为" + customTimeAvg + ",";
                String analysisResultDescriptionNormal = "未见数据异常波动现象";
                //时间
                Date date = new Date();
                warningRecord1.setSystemType(earlyWarningSettingDto.getSystemTypeName());
                warningRecord1.setPointNo(earlyWarningSettingDto.getPointNo());
                warningRecord1.setBaseStation(earlyWarningSettingDto.getBaseStationName());
                warningRecord1.setSensorType(earlyWarningSettingDto.getSensorTypeName());
                warningRecord1.setAnalysisResult("0");
                warningRecord1.setAnalysisResultDescription(analysisResultDescriptionNormal);
                warningRecord1.setAnalysisTime(date);
                //平均值比较
                if ((threeAvg - customTimeAvg) > warningThreshold && (oneAvg - customTimeAvg) > warningThreshold) {
                    //自定义时间的值小于三天和一天的值超过阈值
                    analysisResultDescriptionWarning = analysisResultDescriptionWarning + "比最近3日的均值点" + "(" + threeAvg + ")" + "降低了" + Double.valueOf(df.format(threeAvg - customTimeAvg)) + "," + "比最近1日的均值点" + "(" + oneAvg + ")" + "降低了" + Double.valueOf(df.format(oneAvg - customTimeAvg));
                    warningRecord1.setWarningStartTime(date);
                    warningRecord1.setAnalysisResult("1");
                    warningRecord1.setAnalysisResultDescription(analysisResultDescriptionWarning);
                }
                if ((customTimeAvg - oneAvg) > warningThreshold && (customTimeAvg - threeAvg) > warningThreshold) {
                    //自定义时间的值大于三天和一天的值超过阈值
                    analysisResultDescriptionWarning = analysisResultDescriptionWarning + "比最近3日的均值点" + "(" + threeAvg + ")" + "增加了" + Double.valueOf(df.format(customTimeAvg - threeAvg)) + "," + "比最近1日的均值点" + "(" + oneAvg + ")" + "增加了" + Double.valueOf(df.format(customTimeAvg - oneAvg));
                    warningRecord1.setWarningStartTime(date);
                    warningRecord1.setAnalysisResult("1");
                    warningRecord1.setAnalysisResultDescription(analysisResultDescriptionWarning);
                }
                warningRecordService.insertWarningRecord(warningRecord1);
            }
            if (earlyWarningSettingDto.getSystemTypeName().contains("水文")) {
                //获取阈值
                Double warningThreshold = Double.valueOf(earlyWarningSettingDto.getWarningThreshold());
                //获取近3天平均值
                if (jingxiaHistoryService.selectJingxiaHistoryListThreeAvg(earlyWarningSettingDto.getSensorTypeName(), earlyWarningSettingDto.getBaseStationName()) == null) {
                    return null;
                }
                Double threeAvg = Double.valueOf(jingxiaHistoryService.selectJingxiaHistoryListThreeAvg(earlyWarningSettingDto.getSensorTypeName(), earlyWarningSettingDto.getBaseStationName()));
                //获取近一天平均值
                if (jingxiaHistoryService.selectJingxiaHistoryListOneAvg(earlyWarningSettingDto.getSensorTypeName(), earlyWarningSettingDto.getBaseStationName()) == null) {
                    return null;
                }
                Double oneAvg = Double.valueOf(jingxiaHistoryService.selectJingxiaHistoryListOneAvg(earlyWarningSettingDto.getSensorTypeName(), earlyWarningSettingDto.getBaseStationName()));
                //获取自定义时间平均值
                Double customTimeAvg = null;
                if (earlyWarningSettingDto.getWarningTimeUnitName().equals("小时")) {
                    Double warningTime = Double.valueOf(earlyWarningSettingDto.getWarningTime());
                    String customTimeCount = String.valueOf(warningTime * 3600);
                    if (jingxiaHistoryService.selectJingxiaHistoryListCustomTime(earlyWarningSettingDto.getSensorTypeName(), earlyWarningSettingDto.getBaseStationName(), customTimeCount) == null) {
//                        System.out.println("1324小时");
                        return null;
                    }
                    customTimeAvg = Double.valueOf(jingxiaHistoryService.selectJingxiaHistoryListCustomTime(earlyWarningSettingDto.getSensorTypeName(), earlyWarningSettingDto.getBaseStationName(), customTimeCount));
                }
                if (earlyWarningSettingDto.getWarningTimeUnitName().equals("分钟")) {
                    Double warningTime = Double.valueOf(earlyWarningSettingDto.getWarningTime());
                    String customTimeCount = String.valueOf(warningTime * 60);
                    if (jingxiaHistoryService.selectJingxiaHistoryListCustomTime(earlyWarningSettingDto.getSensorTypeName(), earlyWarningSettingDto.getBaseStationName(), customTimeCount) == null) {
//                        System.out.println("1234分钟");
                        return null;
                    }
                    customTimeAvg = Double.valueOf(jingxiaHistoryService.selectJingxiaHistoryListCustomTime(earlyWarningSettingDto.getSensorTypeName(), earlyWarningSettingDto.getBaseStationName(), customTimeCount));
                }
                if (earlyWarningSettingDto.getWarningTimeUnitName().equals("秒")) {
                    if (jingxiaHistoryService.selectJingxiaHistoryListCustomTime(earlyWarningSettingDto.getSensorTypeName(), earlyWarningSettingDto.getBaseStationName(), earlyWarningSettingDto.getWarningTime()) == null) {
//                        System.out.println("1234秒");
                        return null;
                    }
                    customTimeAvg = Double.valueOf(jingxiaHistoryService.selectJingxiaHistoryListCustomTime(earlyWarningSettingDto.getSensorTypeName(), earlyWarningSettingDto.getBaseStationName(), earlyWarningSettingDto.getWarningTime()));
                }
//                System.out.println("customTimeAvg = " + customTimeAvg);
                //定义分析结果描述
                String analysisResultDescriptionWarning = "检测点最近" + earlyWarningSettingDto.getWarningTime() + earlyWarningSettingDto.getWarningTimeUnitName() + "的平均值为" + customTimeAvg + ",";
                String analysisResultDescriptionNormal = "未见数据异常波动现象";
                //时间
                Date date = new Date();
                warningRecord1.setSystemType(earlyWarningSettingDto.getSystemTypeName());
                warningRecord1.setPointNo(earlyWarningSettingDto.getPointNo());
                warningRecord1.setBaseStation(earlyWarningSettingDto.getBaseStationName());
                warningRecord1.setSensorType(earlyWarningSettingDto.getSensorTypeName());
                warningRecord1.setAnalysisResult("0");
                warningRecord1.setAnalysisResultDescription(analysisResultDescriptionNormal);
                warningRecord1.setAnalysisTime(date);
                //平均值比较
                if ((threeAvg - customTimeAvg) > warningThreshold && (oneAvg - customTimeAvg) > warningThreshold) {
                    //自定义时间的值小于三天和一天的值超过阈值
                    analysisResultDescriptionWarning = analysisResultDescriptionWarning + "比最近3日的均值点" + "(" + threeAvg + ")" + "降低了" + Double.valueOf(df.format(threeAvg - customTimeAvg)) + "," + "比最近1日的均值点" + "(" + oneAvg + ")" + "降低了" + Double.valueOf(df.format(oneAvg - customTimeAvg));
                    warningRecord1.setWarningStartTime(date);
                    warningRecord1.setAnalysisResult("1");
                    warningRecord1.setAnalysisResultDescription(analysisResultDescriptionWarning);
                }
                if ((customTimeAvg - oneAvg) > warningThreshold && (customTimeAvg - threeAvg) > warningThreshold) {
                    //自定义时间的值大于三天和一天的值超过阈值
                    analysisResultDescriptionWarning = analysisResultDescriptionWarning + "比最近3日的均值点" + "(" + threeAvg + ")" + "增加了" + Double.valueOf(df.format(customTimeAvg - threeAvg)) + "," + "比最近1日的均值点" + "(" + oneAvg + ")" + "增加了" + Double.valueOf(df.format(customTimeAvg - oneAvg));
                    warningRecord1.setWarningStartTime(date);
                    warningRecord1.setAnalysisResult("1");
                    warningRecord1.setAnalysisResultDescription(analysisResultDescriptionWarning);
                }
                warningRecordService.insertWarningRecord(warningRecord1);
            }
            return earlyWarningSettingDto;
        }).collect(Collectors.toList());
        return warningRecordMapper.selectWarningRecordListAll(warningRecord);
    }

    //处理earlyWarningSettingList
    public List<EarlyWarningSettingDto> getEarlyWarningSettingDto() {
        //获取预警设置list
        List<EarlyWarningSetting> earlyWarningSettingList = earlyWarningSettingService.selectEarlyWarningSettingList(new EarlyWarningSetting());
        List<EarlyWarningSettingDto> collect = earlyWarningSettingList.stream().map(earlyWarningSetting -> {
            EarlyWarningSettingDto earlyWarningSettingDto = new EarlyWarningSettingDto();
            BeanUtils.copyProperties(earlyWarningSetting, earlyWarningSettingDto);
            //报警区域
            earlyWarningSettingDto.setBaseStationName(sysDictDataMapper.selectDictLabel("alarm_area", earlyWarningSetting.getBaseStation()));
            //传感器类型
            earlyWarningSettingDto.setSensorTypeName(sysDictDataMapper.selectDictLabel("sensor_type", earlyWarningSetting.getSensorType()));
            //系统类型
            earlyWarningSettingDto.setSystemTypeName(sysDictDataMapper.selectDictLabel("system_type", earlyWarningSetting.getSystemType()));
            //单位
            earlyWarningSettingDto.setWarningTimeUnitName(sysDictDataMapper.selectDictLabel("warning_time_unit", earlyWarningSetting.getWarningTimeUnit()));
            return earlyWarningSettingDto;
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 新增预警记录
     *
     * @param warningRecord 预警记录
     * @return 结果
     */
    @Override
    public int insertWarningRecord(WarningRecord warningRecord) {
        warningRecord.setWarningRecordId(String.valueOf(new SnowflakeIdUtils(5, 8).nextId()));
        warningRecord.setCreateTime(DateUtils.getNowDate());
        return warningRecordMapper.insertWarningRecord(warningRecord);
    }

    /**
     * 修改预警记录
     *
     * @param warningRecord 预警记录
     * @return 结果
     */
    @Override
    public int updateWarningRecord(WarningRecord warningRecord) {
        warningRecord.setUpdateTime(DateUtils.getNowDate());
        return warningRecordMapper.updateWarningRecord(warningRecord);
    }

    /**
     * 批量删除预警记录
     *
     * @param warningRecordIds 需要删除的预警记录主键
     * @return 结果
     */
    @Override
    public int deleteWarningRecordByWarningRecordIds(String[] warningRecordIds) {
        return warningRecordMapper.deleteWarningRecordByWarningRecordIds(warningRecordIds);
    }

    /**
     * 删除预警记录信息
     *
     * @param warningRecordId 预警记录主键
     * @return 结果
     */
    @Override
    public int deleteWarningRecordByWarningRecordId(String warningRecordId) {
        return warningRecordMapper.deleteWarningRecordByWarningRecordId(warningRecordId);
    }
}
